package JUC.第05章_中断机制_LockSupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class B2_Lock的Condition介绍 {
    public static void main(String[] args) {

        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Thread a = new Thread(()->{
            lock.lock();

            System.out.println("进入->" + Thread.currentThread().getName());
            try {
                condition.await();//必须在自己的 锁块里
                System.out.println(Thread.currentThread().getName() + " 被唤醒->");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        },"a");
        a.start();

        try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}

        Thread b = new Thread(()->{
            lock.lock();
            System.out.println("进入->" + Thread.currentThread().getName());
            condition.signal();//必须在自己的 锁块里,而且必须在 wait 之后
            System.out.println(Thread.currentThread().getName() + " 唤醒->" + a.getName());
            try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            lock.unlock();

        },"b");
        b.start();

    }
}
